import axios from 'axios'
import { nextTick } from 'vue'
import { ElLoading } from 'element-plus'

let loadingInstance

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // console.log('before request', config)
    loadingInstance = ElLoading.service({ fullscreen: true })

    const token = localStorage.getItem('token')
    config.headers.Authorization = `Bearer ${token}`
    return config
}, function (error) {
    // 对请求错误做些什么
    // 失败也要关闭等待诓
    nextTick(() => {
        loadingInstance.close()
    })
    console.log('request error: ', error)
    return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    // console.log('before response', response)
    const { authorization } = response.headers
    authorization && localStorage.setItem('token', authorization)
    nextTick(() => {
        loadingInstance.close()
    })
    return response
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // console.log('response error: ', error)
    // 失败也要关闭等待诓
    nextTick(() => {
        loadingInstance.close()
    })
    const { status } = error.response
    if (status === 401) {
        localStorage.removeItem('token')
        window.location.href = '#/login'
    }
    return Promise.reject(error)
})